package com.niiwoo.civet.trade.service.dubbo.kaola;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.civet.trade.dao.entity.KaoLaSignNotifyRecord;
import com.niiwoo.civet.trade.dao.mapper.KaoLaSignNotifyRecordMapperExt;
import com.niiwoo.civet.trade.dto.request.kaola.KaoLaDebtResultNotifyRequestDTO;
import com.niiwoo.civet.trade.dto.request.kaola.KaoLaSignNotifyUrlDTO;
import com.niiwoo.civet.trade.dto.response.kaola.KaoLaBaseResponseDTO;
import com.niiwoo.civet.trade.dto.response.kaola.KaoLaCreditAssignmentResponseDTO;
import com.niiwoo.civet.trade.service.koala.KaoLaLiCaiContractDubboService;
import com.niiwoo.civet.trade.service.local.contract.KaoLaLiCaiContract;
import com.niiwoo.civet.user.dto.request.SimpleOrgInfo;
import com.niiwoo.civet.user.enums.OrganizationEnum;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.tripod.base.component.AsyncHttpClients;
import com.niiwoo.tripod.fadada.FadadaService;
import com.niiwoo.tripod.fadada.dto.request.ExtSignRequestDTO;
import com.niiwoo.tripod.fadada.enums.SignWayEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Objects;
import java.util.concurrent.Future;

/**
 * 考拉理财合同签署dubbo服务实现
 *
 * @author liming
 * @date 2017-12-29 12:03
 */
@Slf4j
@Service(version = "1.0.0")
public class KaoLaLiCaiContractDubboServiceImpl implements KaoLaLiCaiContractDubboService {

    @Value("${fadada-multi-platform-contract-sign-result-notifyUrl}")
    private String fadadaNotifyUrl;

    @Autowired
    private FadadaService fadadaService;



    @Autowired
    private KaoLaSignNotifyRecordMapperExt kaoLaSignNotifyRecordMapperExt;

    @Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;

    @Autowired
    private AsyncHttpClients asyncHttpClients;

    @Autowired
    private KaoLaLiCaiContract kaoLaLiCaiContract;

    @Override
    public KaoLaCreditAssignmentResponseDTO kaolaSignNotify(KaoLaSignNotifyUrlDTO kaoLaSignNotifyUrlDTO) {
        return kaoLaLiCaiContract.kaolaSignNotify(kaoLaSignNotifyUrlDTO);

    }

    /**
     * 自动签署法大大推送的代签合同
     *
     * @param signNotifyRecordId  (t_tc_kaola_sign_notify_record:id)
     * @return
     */
    @Override
    public KaoLaBaseResponseDTO autoSignForKaolaDebt(Long signNotifyRecordId) {

        log.info("考拉债权转让协议合同签署业务层,signNotifyRecordId={}", signNotifyRecordId);
        KaoLaBaseResponseDTO responseDTO = new KaoLaBaseResponseDTO();
        responseDTO.setResult(KaoLaBaseResponseDTO.KaoLaBaseResponseResultEnum.FAIL.getCode());
        responseDTO.setMessage(KaoLaBaseResponseDTO.KaoLaBaseResponseResultEnum.FAIL.getDescription());
        if (!HintManagerHolder.isMasterRouteOnly()) {
            HintManagerHolder.clear();
            HintManager hintManager = HintManager.getInstance();
            hintManager.setMasterRouteOnly();
        }
        KaoLaSignNotifyRecord kaolaSignNotifyRecord = kaoLaSignNotifyRecordMapperExt.selectByPrimaryKey(signNotifyRecordId);
        if(Objects.isNull(kaolaSignNotifyRecord)){
            log.error("考拉债权转让协议合同签署业务层,signNotifyRecordId={},签署失败,原因是KaolaSignNotifyRecord不存在.", signNotifyRecordId);
            return responseDTO;
        }

        /*
         * 新旧业务逻辑变更记录:
         *      旧:担保公司在你我金融对应一个用户,通过用户基础信息表取到担保公司的CA证书和userId
         *      新:担保公司不在你我金融平台生成用户,无法取到userId,使用表t_uc_organization_info主键替代useId
         */
        SimpleOrgInfo org = organizationDubboService.getSimpleOrgInfoByType(OrganizationEnum.GUARANTEE_ORG);
        if(Objects.isNull(org)) {
            log.error("考拉债权转让协议合同签署业务层,signNotifyRecordId={},签署失败,原因是担保公司不存在.", signNotifyRecordId);
            return responseDTO;
        }

        log.info("考拉债权转让协议合同签署业务层,signNotifyRecordId={},交易号={}", signNotifyRecordId,kaolaSignNotifyRecord.getTransactionId());

        ExtSignRequestDTO extSignRequestDTO = new ExtSignRequestDTO();
        extSignRequestDTO.setSendAppId(kaolaSignNotifyRecord.getSendAppId());//合同发起方(考拉理财)在法大大的app_id
        extSignRequestDTO.setTransactionId(kaolaSignNotifyRecord.getTransactionId());
        extSignRequestDTO.setPushTransactionId(kaolaSignNotifyRecord.getPushTransactionId());
        extSignRequestDTO.setContractId(kaolaSignNotifyRecord.getContractId());
        extSignRequestDTO.setCustomerId(org.getFadadaCacertId());
        extSignRequestDTO.setUserId(String.valueOf(org.getId()));
        extSignRequestDTO.setIsAuto(SignWayEnum.AUTOMATICSIGN.value());
        extSignRequestDTO.setNotifyUrl(fadadaNotifyUrl);//法大大合同签署结果通知合同接收方(你我金融)地址

        String url = fadadaService.extSignPush(extSignRequestDTO);
        log.info("考拉债权转让协议合同签署业务层,signNotifyRecordId={},接口地址={},交易号={}", signNotifyRecordId,url, extSignRequestDTO.getTransactionId());

        Future<HttpResponse> future = asyncHttpClients.getRequest(url, new FutureCallback<HttpResponse>() {
            @Override
            public void completed(HttpResponse result) {}
            @Override
            public void failed(Exception ex) {}
            @Override
            public void cancelled() {}
        });

        try {
            log.info("考拉债权转让协议合同签署业务层,signNotifyRecordId={},返回结果={}", signNotifyRecordId, EntityUtils.toString(future.get().getEntity(),"UTF-8"));
            if(HttpStatus.SC_OK != future.get().getStatusLine().getStatusCode()){
                return responseDTO;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return responseDTO;
        }

        responseDTO.setResult(KaoLaBaseResponseDTO.KaoLaBaseResponseResultEnum.SUCCESS.getCode());
        responseDTO.setMessage(KaoLaBaseResponseDTO.KaoLaBaseResponseResultEnum.SUCCESS.getDescription());
        return responseDTO;
    }

    /**
     * @description 考拉债权转让协议签署结果异步通知处理
     *
     * @param requestDTO
     * @return
     */
    @Override
    public KaoLaBaseResponseDTO kaolaDebtResultNotify(KaoLaDebtResultNotifyRequestDTO requestDTO) {
        return kaoLaLiCaiContract.kaolaDebtResultNotify(requestDTO);

    }

}
